//
//  IntegralShopViewController.m
//  TerritoryShopkeeper
//
//  Created by 李小龙 on 2017/12/13.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "IntegralShopViewController.h"
#import "GoodsListModel.h"
#import "IntegralTableViewCell.h"
#import "TitlesStrView.h"
#import "GoodsDetailViewController.h"
#import "SearchCacheViewController.h"
#import "ShopcartModel.h"
#import "ShopcartOrderViewController.h"
#import "ClassifyThirdModel.h"

@interface IntegralShopViewController ()<UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headerTopLayout;
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;
@property (weak, nonatomic) IBOutlet UILabel *headerIntegralLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) TitlesStrView *titleView;
@property (nonatomic, strong) NSMutableArray<ClassifyThirdModel *> *titleArray;

@property (nonatomic, strong) NSMutableArray<GoodsListModel *> *tableArray;
@property (nonatomic, assign) NSInteger page;

@end

@implementation IntegralShopViewController
#pragma mark _Get
- (NSMutableArray<GoodsListModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
- (TitlesStrView *)titleView {
    if (!_titleView) {
        _titleView = [[TitlesStrView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 32)];
    }
    return _titleView;
}
- (NSMutableArray<ClassifyThirdModel *> *)titleArray {
    if (!_titleArray) {
        _titleArray = [[NSMutableArray alloc] init];
    }
    return _titleArray;
}
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] init];
        [_searchView.layer setCornerRadius:14];
        _searchView.clipsToBounds = YES;
        [_searchView setBackgroundColor:[UIColor whiteColor]];
    }
    return _searchView;
}
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        //[_searchBar changeLeftPlaceholder:@"搜索你想要的"];
        _searchBar.placeholder = @"搜索你感兴趣的商品";
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 28;
        [searchField.layer setCornerRadius:14];
        //[searchField.layer setBorderWidth:0.5];
        [searchField.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        searchField.layer.masksToBounds = YES;
        searchField.font = TextPingFangFontSize(14);
        
    }
    return _searchBar;
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureNavigation];
    
    [self createUI];
    
    [self getTitleNetData];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavigationController];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}
#pragma mark - Action
- (void)configureNavigation {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    
    [self.searchView addSubview:self.searchBar];
    self.searchView.frame = CGRectMake(0, 0, ScreenWidth - 15 * 4 - 28 * 2, 28);
    self.searchBar.frame = CGRectMake(0, 0, self.searchView.width, 28);
    self.navigationItem.titleView = self.searchView;
}
- (void)rightItemClick {
    [self disMissSelf];
}

- (void)createUI {
    self.page = 1;
    [self.headerImageView sd_setImageWithURL:GetUrl([UserInfo shareInstance].user.mimg) placeholderImage:PlaceholderImageHeader];
    [self.headerImageView setCircleWithColor:[UIColor whiteColor] borderWidth:2 cornerRadius:self.headerImageView.width/2.0];
    
    NSString *integralStr = [NSString stringWithFormat:@"%@积分",TextIsNotNil([UserInfo shareInstance].user.mintegral)?[UserInfo shareInstance].user.mintegral:@"0"];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:integralStr];
    [attributedStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(32),
                                   NSForegroundColorAttributeName:[UIColor whiteColor]}
                           range:NSMakeRange(0, integralStr.length)];
    [attributedStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(14),
                                   NSForegroundColorAttributeName:[UIColor whiteColor]}
                           range:[integralStr rangeOfString:@"积分"]];
    [self.headerIntegralLabel setAttributedText:attributedStr];
    
    self.titleView.top = self.headerView.bottom;
    [self.titleView setBorderWithTop:NO left:NO bottom:YES right:NO borderColor:[UIColor colorWithHex:0xE5E5E5 alpha:1] borderWidth:1];
    [self.view addSubview:self.titleView];
    
    __block typeof(self) blockSelf = self;
    self.titleView.block = ^(NSInteger index) {
        _page = 1;
        [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
        [blockSelf getNetData];
    };
    
    [self createTable];
}
static NSString *integralTableIdentifier = @"integralTableIdentifier";
- (void)createTable {
    
    [self.tableView clearExtendCellLine];
    [self.tableView registerNib:[UINib nibWithNibName:@"IntegralTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:integralTableIdentifier];
    
    __block typeof(self) blockSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [blockSelf getNetData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [blockSelf getNetData];
    }];
    [self.tableView.mj_footer setHidden:YES];
}
- (void)updateTitleView {
    NSMutableArray *titleStrArr = [[NSMutableArray alloc] init];
    for (ClassifyThirdModel *model in self.titleArray) {
        [titleStrArr addObject:model.gtrcname];
    }
    [self.titleView setupWithTitleStrsArr:titleStrArr withIndex:self.titleView.currentIndex];
}
- (void)exchangeButtonAction:(GoodsListModel *)model {
    
    ShopcartOrderViewController *shopcartVC = [[ShopcartOrderViewController alloc] init];
    shopcartVC.isHaveWorldwide = NO;
    shopcartVC.type = ShopcartOrderTypeIntegral;
    ShopcartModel *shopcartModel = [ShopcartModel mj_objectWithKeyValues:model];
    ShopcartClassifyModel *classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[shopcartModel]}];
    shopcartVC.tableArray = [[NSMutableArray alloc] initWithObjects:classifyModel, nil];
    [self.navigationController pushViewController:shopcartVC animated:YES];
}

- (void)gotoSearchVC {
    SearchCacheViewController *searchVC = [[SearchCacheViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
#pragma mark - 网络请求
- (void)getTitleNetData {
//    //MARK:测试
//    [self.titleArray addObjectsFromArray:@[@"精选",@"新品", @"手镯",@"项链",@"戒指",@"耳环", @"源氏", @"小美", @"士兵76", @"路霸", @"法鸡", @"炮台", @"半藏", @"大锤", @"DJ", @"毛妹", @"闪烁", @"寡妇", @"死神", @"炸弹人", @"猩猩"]];
//    [self updateTitleView];
//    [self getNetData];
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
//    [self.tableView reloadData];
//    return;
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_Integral_Class parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [blockSelf.titleArray removeAllObjects];
            for (NSDictionary *dic in responseObject[@"data"]) {
                ClassifyThirdModel *model = [ClassifyThirdModel mj_objectWithKeyValues:dic];
                [blockSelf.titleArray addObject:model];
            }
            [blockSelf updateTitleView];
            [blockSelf getNetData];
        } else {
            [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)getNetData {
    if (self.titleArray.count > 0) {
        NSString *gtrcid = self.titleArray[self.titleView.currentIndex].gtrcid;
        __block typeof(self) blockSelf = self;
        [MYAFNetworking POST:URL_Get_Integral_Goods_List parameters:@{@"pageSize":PageSize,@"pageNumber":@(self.page),@"gtrcid":gtrcid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
            [blockSelf endRefresh];
            if ([responseObject[@"code"] isEqualToString:@"200"]) {
                NSDictionary *dic = responseObject;
                [blockSelf getNetSuccess:dic];
            } else {
                [blockSelf getNetFailure];
                [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            [blockSelf endRefresh];
            [blockSelf getNetFailure];
            [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
            [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
        }];
    } else {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        //[self getTitleNetData];
    }
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    if (_page != 1) {
        _page--;
    }
}
- (void)getNetSuccess:(NSDictionary *)dics {
    [self.tableView.mj_footer setHidden:YES];
    
    if ([dics[@"data"][@"totalRow"] integerValue] > self.tableArray.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    if (self.page == 1) {
        [self.tableArray removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    NSArray *list = dics[@"data"][@"list"];
    if (list.count == 0 && self.page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    for (NSDictionary *dic in list) {
        GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:dic];
        [self.tableArray addObject:model];
    }
    [self.tableView reloadData];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IntegralTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:integralTableIdentifier forIndexPath:indexPath];
    
    GoodsListModel *model = self.tableArray[indexPath.row];
    [cell.iconImageView sd_setImageWithURL:GetUrl(model.gimg) placeholderImage:PlaceholderImageSmall changeContentModel:UIViewContentModeScaleAspectFill];
    [cell.titleLabel setText:model.gname];
    
    NSString *integralStr = [NSString stringWithFormat:@"%@积分",model.gintegral];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:integralStr];
    [attributedStr addAttributes:@{NSFontAttributeName:TextPingFangMediumFontSize(20),
                                   NSForegroundColorAttributeName:[UIColor ThemeColor]}
                           range:NSMakeRange(0, integralStr.length)];
    [attributedStr addAttributes:@{NSFontAttributeName:TextPingFangFontSize(10),
                                   NSForegroundColorAttributeName:[UIColor ThemeColor]}
                           range:[integralStr rangeOfString:@"积分"]];
    [cell.integralLabel setAttributedText:attributedStr];
    
    [cell.countLabel setText:[NSString stringWithFormat:@"剩余%@件",model.allgastock]];
    
    __block typeof(self) blockSelf = self;
    cell.block = ^{
        if (!model.isshelves) {
            [MBProgressHUD showError:blockSelf.view title:@"该商品已下架" code:@"" animated:YES];
            return;
        }
        
        GoodsDetailViewController *goodDetailVC = [[GoodsDetailViewController alloc] init];
        goodDetailVC.gid = model.gid;
        goodDetailVC.type = GoodsDetailViewControllerTypeForCredits;
        [blockSelf.navigationController pushViewController:goodDetailVC animated:YES];
        //[blockSelf exchangeButtonAction:model];
    };
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 132;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GoodsListModel *model = self.tableArray[indexPath.row];
    if (!model.isshelves) {
        [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
        return;
    }
    
    GoodsDetailViewController *goodDetailVC = [[GoodsDetailViewController alloc] init];
    goodDetailVC.gid = model.gid;
    goodDetailVC.type = GoodsDetailViewControllerTypeForCredits;
    [self.navigationController pushViewController:goodDetailVC animated:YES];
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无积分商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    _page = 1;
    [self getNetData];
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    SearchCacheViewController *searchCacheVC = [[SearchCacheViewController alloc] init];
    searchCacheVC.type = SearchCacheViewControllerTypeForIntegral;
    [self.navigationController pushViewController:searchCacheVC animated:YES];
    return NO;
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
